from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from sqlalchemy import func
from app.database import get_db
from app.models.question import Question, QuestionType
from app.models.exam import Exam
from app.models.user import User, UserRole
from app.schemas.question import QuestionCreate, QuestionUpdate, QuestionResponse, QuestionForStudent
from app.auth import get_current_active_user, get_current_teacher

router = APIRouter()

@router.get("/", response_model=List[QuestionResponse])
async def get_questions(
    exam_id: Optional[int] = Query(None, description="考试ID筛选"),
    question_type: Optional[QuestionType] = Query(None, description="题型筛选"),
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取题目列表"""
    query = db.query(Question)
    
    if exam_id:
        query = query.filter(Question.exam_id == exam_id)
        
        # 检查权限
        exam = db.query(Exam).filter(Exam.id == exam_id).first()
        if exam and current_user.role == UserRole.TEACHER and exam.created_by != current_user.id:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="只能查看自己创建的考试的题目"
            )
    
    if question_type:
        query = query.filter(Question.question_type == question_type)
    
    questions = query.offset(skip).limit(limit).all()
    return questions

@router.get("/exam/{exam_id}/student", response_model=List[QuestionForStudent])
async def get_exam_questions_for_student(
    exam_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取考试题目（学生端）- 不包含正确答案"""
    from datetime import datetime
    
    exam = db.query(Exam).filter(Exam.id == exam_id).first()
    if not exam:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="考试不存在"
        )
    
    # 检查考试状态
    now = datetime.utcnow()
    if exam.status != "published" or now < exam.start_time or now > exam.end_time:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="当前时间不能参加该考试"
        )
    
    questions = db.query(Question).filter(Question.exam_id == exam_id).order_by(Question.order_num).all()
    return questions

@router.get("/{question_id}", response_model=QuestionResponse)
async def get_question(
    question_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取题目详情"""
    question = db.query(Question).filter(Question.id == question_id).first()
    if not question:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="题目不存在"
        )
    
    # 检查权限
    exam = db.query(Exam).filter(Exam.id == question.exam_id).first()
    if exam and current_user.role == UserRole.TEACHER and exam.created_by != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只能查看自己创建的考试的题目"
        )
    
    return question

@router.post("/", response_model=QuestionResponse)
async def create_question(
    question_data: QuestionCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_teacher)
):
    """创建题目"""
    # 检查考试是否存在
    exam = db.query(Exam).filter(Exam.id == question_data.exam_id).first()
    if not exam:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="考试不存在"
        )
    
    # 检查权限
    if current_user.role == UserRole.TEACHER and exam.created_by != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只能为创建的考试添加题目"
        )
    
    db_question = Question(**question_data.dict())
    db.add(db_question)
    db.commit()
    db.refresh(db_question)
    
    # 更新考试题目数量
    question_count = db.query(Question).filter(Question.exam_id == question_data.exam_id).count()
    exam.question_count = question_count
    db.commit()
    
    return db_question

@router.put("/{question_id}", response_model=QuestionResponse)
async def update_question(
    question_id: int,
    question_data: QuestionUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_teacher)
):
    """更新题目"""
    question = db.query(Question).filter(Question.id == question_id).first()
    if not question:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="题目不存在"
        )
    
    # 检查权限
    exam = db.query(Exam).filter(Exam.id == question.exam_id).first()
    if exam and current_user.role == UserRole.TEACHER and exam.created_by != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只能更新自己创建的考试的题目"
        )
    
    for field, value in question_data.dict(exclude_unset=True).items():
        setattr(question, field, value)
    
    db.commit()
    db.refresh(question)
    return question

@router.delete("/{question_id}")
async def delete_question(
    question_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_teacher)
):
    """删除题目"""
    question = db.query(Question).filter(Question.id == question_id).first()
    if not question:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="题目不存在"
        )
    
    # 检查权限
    exam = db.query(Exam).filter(Exam.id == question.exam_id).first()
    if exam and current_user.role == UserRole.TEACHER and exam.created_by != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只能删除自己创建的考试的题目"
        )
    
    db.delete(question)
    db.commit()
    
    # 更新考试题目数量
    question_count = db.query(Question).filter(Question.exam_id == question.exam_id).count()
    exam.question_count = question_count
    db.commit()
    
    return {"message": "题目删除成功"}

@router.get("/exam/{exam_id}/count")
async def get_question_count(
    exam_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_teacher)
):
    """获取考试题目数量"""
    exam = db.query(Exam).filter(Exam.id == exam_id).first()
    if not exam:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="考试不存在"
        )
    
    # 检查权限
    if current_user.role == UserRole.TEACHER and exam.created_by != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只能查看自己创建的考试的统计信息"
        )
    
    count = db.query(Question).filter(Question.exam_id == exam_id).count()
    return {"count": count}